import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { AutoSizer, List, ListRowProps } from 'react-virtualized';
import { Options, IOption } from './DropdownList';

export interface IVirtualizedListProps {
  style?: React.CSSProperties;
  onItemClick: (option: IOption, index: number) => void;
  options: Options;
  value: IOption[];
}

export class VirtualizedList extends React.Component<IVirtualizedListProps, {}> {
  public static propTypes = {
    style: PropTypes.object,
  };

  constructor(props: IVirtualizedListProps) {
    super(props);
    this.listRenderer = this.listRenderer.bind(this);
  }

  public listRenderer({ index, style, key }: ListRowProps) {
    const { options, onItemClick, value } = this.props;
    const option = options[index];
    const isSelected = value.find((val) => val.value === option.value);
    return (
      <li className={classNames('br-select__menu-item', {
        'br-select__menu-item--selected': isSelected as boolean,
        'br-select__menu-item--disabled': option.disabled,
      })} key={key} style={style}
        onClick={(e) => !option.disabled && onItemClick(option, index)}
        title={option.label}
      >
        {option.label}
      </li>
    );
  }

  public render() {
    const { options } = this.props;
    const rowHeight = 26;
    return (
      <AutoSizer style={this.props.style}>
        {({ height, width }) => (
          <List
            height={height}
            width={width}
            rowHeight={rowHeight}
            rowCount={options.length}
            rowRenderer={this.listRenderer}
            overscanRowCount={10}
            style={{ outline: 0 }}
          />
        )}
      </AutoSizer>
    );
  }
}
